package com.itheima.interceptor;


import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

public class MyInterceptors implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response,
                             Object handler) throws IOException {
        Object user = request.getSession().getAttribute("user");

        //3 判断如果user!=null,说明登录成功，将user保存到session
        if(user == null){
            Map<String,String> errMap = new HashMap<>();
            errMap.put("error","没有登入。快滚");


            ObjectMapper objectMapper = new ObjectMapper();
            objectMapper.writeValue(response.getWriter(),errMap);
        }
        return true;
    }
}
